import pymysql
import traceback
from common.log import Log

class MySql:
    def __init__(self,host,user,password,db,charset='utf-8',autocommit=True,port=3306,cursor_type = 'dict'):
        port = int(port)
        self.coon = pymysql.connect(host = host,
                                    user=user,
                                    password=password,
                                    db=db,
                                    charset = charset,
                                    autocommit = autocommit,
                                    port = port
        )
        if cursor_type =='dict':
            self.cursor = self.coon.cursor(pymysql.cursors.DictCursor)
        else:
            self.cursor = self.coon.cursor()
        Log.info('开始连接数据库')
    def __del__(self):
        Log.info('关闭数据库连接')
        self.__close()

    def excute(self,sql):
        try:
            self.cursor.excute(sql)
        except Exception:
            Log.error('sql出错,sql为{}',sql)
            Log.error(traceback.format_exc())

    def fetchone(self,sql):
        self.fetchone(sql)
        return self.cursor.fetchone()

    def fetchall(self,sql):
        self.fetchall(sql)
        return self.cursor.fetchall()

    def __close(self):
        self.cursor.close()
        self.coon.close()

if __name__ =="__main__":
    pass